package com.shop.auth.service.impl;

import com.shop.auth.dto.response.JwtResponse;
import com.shop.auth.service.AuthService;
import com.shop.common.enums.ExceptionEnum;
import com.shop.common.exception.OperationException;
import com.shop.security.utils.JwtUtils;
import com.shop.servlet.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;
import com.shop.auth.service.AuthService;
import com.shop.security.exception.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public JwtResponse login(String username, String password) {
        // 1. 调用Spring Security的认证管理器进行用户名密码验证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password)
        );
        // 2. 认证通过，返回用户名
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String jwt = jwtUtils.createToken(loginUser.getUsername());
        return new JwtResponse(jwt, loginUser.getId(), loginUser.getUsername(), loginUser.getEmail());
    }
}
